<template>
  <div class="withdraw-audit-page">
    <!-- 页面标题 -->
    <div class="page-title">提现审核</div>
    
    <!-- 统计信息卡片 -->
    <div class="stats-container">
      <div class="stat-card">
        <div class="stat-title">待审核</div>
        <div class="stat-value">{{ stats.pending }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">已审核</div>
        <div class="stat-value">{{ stats.audited }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">审核总额</div>
        <div class="stat-value">¥{{ formatAmount(stats.totalAmount) }}</div>
      </div>
    </div>
    
    <!-- 筛选标签 -->
    <div class="filter-tabs">
      <div 
        v-for="tab in filterTabs" 
        :key="tab.value"
        class="filter-tab"
        :class="{ active: activeFilter === tab.value }"
        @click="setActiveFilter(tab.value)"
      >
        {{ tab.label }}
      </div>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-form">
      <div class="form-row">
        <div class="form-item">
          <input 
            type="text" 
            class="form-input"
            v-model.trim="searchForm.keyword" 
            placeholder="编号、姓名或关键字"
            @keyup.enter="handleSearch"
          >
        </div>
        <div class="form-item">
          <div class="date-range">
            <input 
              type="date" 
              class="form-input"
              v-model="searchForm.startDate"
              max="2025-09-29"
            >
            <span class="date-separator">至</span>
            <input 
              type="date" 
              class="form-input"
              v-model="searchForm.endDate"
              max="2025-09-29"
            >
          </div>
        </div>
        <div class="form-item">
          <select class="form-select" v-model="searchForm.status">
            <option value="">全部</option>
            <option value="pending">待审核</option>
            <option value="approved">待打款</option>
            <option value="rejected">已驳回</option>
            <option value="paid">已打款</option>
            <option value="invalid">无效</option>
          </select>
        </div>
        <div class="form-actions">
          <button class="btn btn-primary" @click="handleSearch">
            <i class="icon-search"></i> 搜索
          </button>
          <button class="btn btn-secondary" @click="handleReset">
            <i class="icon-reset"></i> 重置
          </button>
          <button class="btn btn-danger" @click="handleDelete">
            <i class="icon-delete"></i> 删除
          </button>
          <button class="btn btn-warning" @click="handleExport">
            <i class="icon-export"></i> 导出
          </button>
        </div>
      </div>
    </div>
    
    <!-- 批量操作按钮 -->
    <div class="batch-actions" v-if="selectedRows.length > 0">
      <span class="batch-info">已选择 {{ selectedRows.length }} 项</span>
      <button class="btn btn-sm btn-primary" @click="handleBatchApprove">
        <i class="icon-approve"></i> 批量通过
      </button>
      <button class="btn btn-sm btn-danger" @click="handleBatchReject">
        <i class="icon-reject"></i> 批量驳回
      </button>
      <button class="btn btn-sm btn-warning" @click="handleBatchInvalid">
        <i class="icon-invalid"></i> 批量无效
      </button>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-container">  
      <div class="table-wrapper">
        <table class="data-table">
          <thead>
            <tr>
              <th class="checkbox-col">
                <input 
                  type="checkbox" 
                  :checked="isAllSelected"
                  @change="toggleSelectAll"
                  :disabled="loading"
                >
              </th>
              <th>编号</th>
              <th>申请人</th>
              <th>联系方式</th>
              <th>申请时间</th>
              <th>提现金额</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="row in paginatedData" 
              :key="row.id"
              :class="{ selected: isRowSelected(row), 'row-disabled': row.status !== 0 }"
            >
              <td class="checkbox-col">
                <input 
                  type="checkbox" 
                  :checked="isRowSelected(row)"
                  @change="toggleRowSelection(row)"
                  :disabled="row.status !== 0 || loading"
                >
              </td>
              <td>{{ row.id }}</td>
              <td>{{ row.userName }}</td>
              <td>{{ row.phone }}</td>
              <td>{{ formatDateTime(row.applyTime) }}</td>
              <td>¥{{ formatAmount(row.amount) }}</td>
              <td>
                <span 
                  class="status-badge"
                  :class="row.statusClass"
                >
                  {{ row.statusText }}
                </span>
              </td>
              <td>
                <div class="action-buttons">
                  <button 
                    class="btn btn-sm btn-primary" 
                    @click="handleApprove(row)"
                    v-if="row.status === 0"
                    :disabled="loading"
                  >
                    <i class="icon-approve"></i> 通过
                  </button>
                  <button 
                    class="btn btn-sm btn-danger" 
                    @click="handleReject(row)"
                    v-if="row.status === 0"
                    :disabled="loading"
                  >
                    <i class="icon-reject"></i> 驳回
                  </button>
                  <button 
                    class="btn btn-sm btn-warning" 
                    @click="handleInvalid(row)"
                    v-if="row.status === 0"
                    :disabled="loading"
                  >
                    <i class="icon-invalid"></i> 无效
                  </button>
                  <button 
                    class="btn btn-sm btn-success" 
                    @click="handlePay(row)"
                    v-if="row.status === 1"
                    :disabled="loading"
                  >
                    <i class="icon-pay"></i> 打款
                  </button>
                  <button 
                    class="btn btn-sm btn-secondary" 
                    @click="handleRevoke(row)"
                    v-if="row.status === 2"
                    :disabled="loading"
                  >
                    <i class="icon-revoke"></i> 撤销驳回
                  </button>
                  <button class="btn btn-sm btn-text" @click="handleDetail(row)">
                    <i class="icon-detail"></i> 查看详情
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div v-if="loading" class="loading-overlay">
          <div class="loading-spinner"></div>
          <div>加载中...</div>
        </div>
        
        <div v-if="paginatedData.length === 0 && !loading" class="empty-state">
          <i class="icon-empty"></i>
          <div>暂无数据</div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录，显示 {{ paginationStart }} - {{ paginationEnd }} 条
        </div>
        <div class="pagination-controls">
          <select class="page-size-select" v-model="pagination.pageSize" @change="handleSizeChange">
            <option value="10">10条/页</option>
            <option value="20">20条/页</option>
            <option value="50">50条/页</option>
            <option value="100">100条/页</option>
          </select>
          
          <button 
            class="pagination-btn" 
            :disabled="pagination.currentPage === 1 || loading"
            @click="handlePageChange(pagination.currentPage - 1)"
          >
            <i class="icon-prev"></i> 上一页
          </button>
          
          <div class="page-numbers">
            <button 
              v-for="page in visiblePages" 
              :key="page"
              class="page-number"
              :class="{ active: page === pagination.currentPage }"
              @click="handlePageChange(page)"
              :disabled="loading"
            >
              {{ page }}
            </button>
          </div>
          
          <button 
            class="pagination-btn" 
            :disabled="pagination.currentPage === totalPages || loading"
            @click="handlePageChange(pagination.currentPage + 1)"
          >
            下一页 <i class="icon-next"></i>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 确认弹窗 -->
    <div v-if="confirmDialogVisible" class="modal-overlay" @click.self="closeConfirmDialog">
      <div class="modal-content confirm-modal" @click.stop>
        <div class="modal-body">
          <div class="confirm-text">
            {{ confirmMessage }}
          </div>
          <div class="confirm-buttons">
            <button class="btn btn-secondary" @click="closeConfirmDialog">取消</button>
            <button class="btn btn-primary" @click="confirmAction">确认</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 删除确认弹窗 -->
    <div v-if="deleteConfirmVisible" class="modal-overlay" @click.self="closeDeleteConfirm">
      <div class="modal-content delete-confirm-modal" @click.stop>
        <div class="modal-body">
          <div class="delete-confirm-text">
            {{ deleteConfirmMessage }}
          </div>
          <div class="delete-confirm-buttons">
            <button class="btn btn-secondary" @click="closeDeleteConfirm">取消</button>
            <button class="btn btn-danger" @click="confirmDelete">确认删除</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 导出确认弹窗 -->
    <div v-if="exportDialogVisible" class="modal-overlay" @click.self="closeExportDialog">
      <div class="modal-content export-modal" @click.stop>
        <div class="modal-header">
          <h3>导出数据</h3>
          <button class="modal-close" @click="closeExportDialog">×</button>
        </div>
        <div class="modal-body">
          <form class="export-form">
            <div class="form-group">
              <label class="form-label">导出范围</label>
              <div class="radio-group">
                <label class="radio-label">
                  <input type="radio" value="all" v-model="exportForm.range">
                  <span class="radio-custom"></span>
                  全部数据 ({{ pagination.total }} 条)
                </label>
                <label class="radio-label">
                  <input type="radio" value="current" v-model="exportForm.range">
                  <span class="radio-custom"></span>
                  当前页数据 ({{ paginatedData.length }} 条)
                </label>
                <label class="radio-label">
                  <input type="radio" value="selected" v-model="exportForm.range" :disabled="selectedRows.length === 0">
                  <span class="radio-custom"></span>
                  选中数据 ({{ selectedRows.length }} 条)
                </label>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">文件格式</label>
              <div class="radio-group">
                <label class="radio-label">
                  <input type="radio" value="excel" v-model="exportForm.format">
                  <span class="radio-custom"></span>
                  Excel (.xlsx)
                </label>
                <label class="radio-label">
                  <input type="radio" value="csv" v-model="exportForm.format">
                  <span class="radio-custom"></span>
                  CSV (.csv)
                </label>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeExportDialog">取消</button>
          <button class="btn btn-primary" @click="confirmExport" :disabled="exportLoading">
            <i class="icon-export"></i> {{ exportLoading ? '导出中...' : '确认导出' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 审核弹窗 -->
    <div v-if="auditDialogVisible" class="modal-overlay" @click.self="handleCloseAuditDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>审核提现申请 - {{ auditForm.id }}</h3>
          <button class="modal-close" @click="handleCloseAuditDialog">×</button>
        </div>
        <div class="modal-body">
          <form class="audit-form">
            <div class="form-group">
              <label class="form-label">编号</label>
              <input type="text" class="form-input" v-model="auditForm.id" disabled>
            </div>
            <div class="form-group">
              <label class="form-label">申请人</label>
              <input type="text" class="form-input" v-model="auditForm.userName" disabled>
            </div>
            <div class="form-group">
              <label class="form-label">金额</label>
              <div class="amount-input">
                <input type="text" class="form-input" v-model="auditForm.amount" disabled>
                <span class="amount-suffix">元</span>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">审核结果 <span class="required">*</span></label>
              <div class="radio-group">
                <label class="radio-label">
                  <input 
                    type="radio" 
                    value="approve" 
                    v-model="auditForm.result"
                  >
                  <span class="radio-custom"></span>
                  通过
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    value="reject" 
                    v-model="auditForm.result"
                  >
                  <span class="radio-custom"></span>
                  驳回
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    value="invalid" 
                    v-model="auditForm.result"
                  >
                  <span class="radio-custom"></span>
                  无效
                </label>
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">审核意见 <span class="required">*</span></label>
              <textarea 
                class="form-textarea" 
                v-model.trim="auditForm.remark" 
                placeholder="请输入审核意见"
                rows="4"
                maxlength="200"
              ></textarea>
              <div class="textarea-counter">
                {{ auditForm.remark.length }}/200
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="handleCloseAuditDialog">取消</button>
          <button class="btn btn-primary" @click="submitAudit" :disabled="auditLoading">
            <i class="icon-submit"></i> {{ auditLoading ? '提交中...' : '确定' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 打款确认弹窗 -->
    <div v-if="payConfirmVisible" class="modal-overlay" @click.self="closePayConfirm">
      <div class="modal-content pay-confirm-modal" @click.stop>
        <div class="modal-body">
          <div class="pay-confirm-text">
            确认通过该用户的提现申请吗？
          </div>
          <div class="pay-confirm-buttons">
            <button class="btn btn-secondary" @click="closePayConfirm">取消</button>
            <button class="btn btn-primary" @click="confirmPay">确认</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 详情弹窗 -->
    <div v-if="detailDialogVisible" class="modal-overlay" @click.self="closeDetailDialog">
      <div class="modal-content detail-modal" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">详情</h3>
          <button class="modal-close" @click="closeDetailDialog">×</button>
        </div>
        
        <div class="modal-body">
          <!-- 提现信息 -->
          <div class="detail-section">
            <div class="section-title">提现信息</div>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">编号：</span>
                <span class="info-value">{{ currentDetail.id }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">联系方式：</span>
                <span class="info-value">{{ currentDetail.contact }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">申请时间：</span>
                <span class="info-value">{{ formatDateTime(currentDetail.applyTime) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">申请人：</span>
                <span class="info-value">{{ currentDetail.applicant }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">注册时长：</span>
                <span class="info-value">{{ currentDetail.registerDuration }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">提现金额（元）：</span>
                <span class="info-value highlight">¥{{ formatAmount(currentDetail.amount) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">账号：</span>
                <span class="info-value">{{ currentDetail.account }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">状态：</span>
                <span class="info-value status-badge" :class="currentDetail.statusClass">
                  {{ currentDetail.statusText }}
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">提现费用（元）：</span>
                <span class="info-value">¥{{ formatAmount(currentDetail.fee) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">年龄：</span>
                <span class="info-value">{{ currentDetail.age }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">提现微信号：</span>
                <span class="info-value">{{ currentDetail.wechatAccount }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">预计打款（元）：</span>
                <span class="info-value highlight">¥{{ formatAmount(currentDetail.expectedAmount) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">性别：</span>
                <span class="info-value">{{ currentDetail.gender }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">提现方式：</span>
                <span class="info-value">{{ currentDetail.withdrawMethod }}</span>
              </div>
            </div>
          </div>
          
          <!-- 用户积分 -->
          <div class="detail-section">
            <div class="section-title">用户积分</div>
            <div class="points-grid">
              <div class="points-item">
                <span class="points-label">当前积分</span>
                <span class="points-value">
                  <span v-if="currentDetail.pointsLoading" class="loading-text">加载中...</span>
                  <span v-else>{{currentDetail.currentPoints}}</span>
                </span>
              </div>
              <div class="points-item">
                <span class="points-label">历史总积分</span>
                <span class="points-value">
                  <span v-if="currentDetail.pointsLoading" class="loading-text">加载中...</span>
                  <span v-else>{{ formatNumber(currentDetail.totalPoints) }}</span>
                </span>
              </div>
              <div class="points-item">
                <span class="points-label">可提现积分</span>
                <span class="points-value">
                  <span v-if="currentDetail.pointsLoading" class="loading-text">加载中...</span>
                  <span v-else>{{ formatNumber(currentDetail.availablePoints) }}</span>
                </span>
              </div>
              <div class="points-item">
                <span class="points-label">已提现积分</span>
                <span class="points-value">
                  <span v-if="currentDetail.pointsLoading" class="loading-text">加载中...</span>
                  <span v-else>{{ formatNumber(currentDetail.withdrawnPoints) }}</span>
                </span>
              </div>
            </div>
          </div>
          
          <!-- 历史提现记录 -->
          <div class="detail-section">
            <div class="section-title">历史提现</div>
            <table class="history-table">
              <thead>
                <tr>
                  <th>编号</th>
                  <th>提现金额</th>
                  <th>申请时间</th>
                  <th>提现时间</th>
                  <th>状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="record in currentDetail.historyRecords" :key="record.id">
                  <td>{{ record.id }}</td>
                  <td class="highlight">¥{{ formatAmount(record.amount) }}</td>
                  <td>{{ formatDateTime(record.applyTime) }}</td>
                  <td>{{ formatDateTime(record.withdrawTime) }}</td>
                  <td>
                    <span class="status-badge status-paid">已打款</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeDetailDialog">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- 消息提示 -->
    <div v-if="message.visible" class="message" :class="message.type">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { 
  getWithdrawalList, 
  updateWithdrawalStatus, 
  deleteWithdrawal,
  getUserTotalPoints,
  Status
} from '@/api/withdrawal/withdrawal.ts'

// 筛选标签
const filterTabs = [
  { label: '全部', value: '' },
  { label: '待审核', value: 'pending' },
  { label: '待打款', value: 'approved' },
  { label: '已打款', value: 'paid' },
  { label: '已驳回', value: 'rejected' },
  { label: '无效', value: 'invalid' }
]

const activeFilter = ref('')

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  startDate: '',
  endDate: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗显示状态
const confirmDialogVisible = ref(false)
const deleteConfirmVisible = ref(false)
const exportDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const payConfirmVisible = ref(false)
const detailDialogVisible = ref(false)
const loading = ref(false)
const auditLoading = ref(false)
const exportLoading = ref(false)
const detailLoading = ref(false)

// 确认弹窗相关
const confirmMessage = ref('')
const deleteConfirmMessage = ref('')
const confirmActionType = ref('')
const currentActionItem = ref(null)

// 导出表单数据
const exportForm = reactive({
  range: 'current',
  format: 'excel'
})

// 审核表单数据
const auditForm = reactive({
  id: '',
  userName: '',
  amount: 0,
  result: 'approve',
  remark: ''
})

// 打款相关
const currentPayItem = ref(null)

// 消息提示
const message = reactive({
  visible: false,
  text: '',
  type: 'info'
})

// 选中的申请
const selectedRows = ref([])

// 详情数据
const currentDetail = reactive({
  id: '',
  contact: '',
  applyTime: '',
  applicant: '',
  registerDuration: '',
  amount: 0,
  account: '',
  status: 0,
  statusText: '',
  statusClass: '',
  fee: 0,
  age: 0,
  wechatAccount: '',
  expectedAmount: 0,
  gender: '',
  withdrawMethod: '',
  currentPoints: 0,
  totalPoints: 0,
  availablePoints: 0,
  withdrawnPoints: 0,
  historyRecords: [],
  pointsLoading: false
})

// 统计信息
const stats = reactive({
  pending: 0,
  audited: 0,
  totalAmount: 0
})

// 表格数据
const tableData = ref([])

// 获取提现列表数据
const fetchWithdrawalList = async () => {
  try {
    loading.value = true
    
    // 构造请求参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
      startTime: searchForm.startDate || undefined,
      endTime: searchForm.endDate || undefined,
      status: mapFrontendStatusToBackend(searchForm.status) || undefined
    }
    
    console.log('请求参数:', params)
    
    // 发送请求获取数据
    const response = await getWithdrawalList(params)
    
    if (response.code === 200) {
      // 正确访问嵌套的data属性
      const apiData = response.data?.data || {}
      
      // 确保records存在且是数组
      const records = apiData.records || []
      
      console.log('API响应数据:', response)
      console.log('转换前的records:', records)
      
      tableData.value = records.map(item => ({
        id: item.id,
        userId: item.userId || item.id, // 添加用户ID字段
        userName: item.username || '未知用户',
        phone: item.phone || '未知号码',
        applyTime: item.lastApplyTime,
        amount: item.withdrawAmount,
        status: mapBackendStatusToFrontend(item.status),
        statusText: getStatusText(mapBackendStatusToFrontend(item.status)),
        statusClass: getStatusClass(mapBackendStatusToFrontend(item.status))
      }))
      
      console.log('转换后的数据:', tableData.value)
      
      // 更新分页信息
      pagination.total = apiData.total || 0
      pagination.currentPage = apiData.current || 1
      pagination.pageSize = apiData.size || pagination.pageSize
      
      // 更新统计信息
      updateStats()
    } else {
      showMessage(response.msg || '获取数据失败', 'error')
    }
  } catch (error) {
    console.error('获取提现申请列表失败:', error)
    showMessage('获取数据失败，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

// 获取用户积分数据
const fetchUserPoints = async (userId) => {
  try {
    currentDetail.pointsLoading = true
    console.log('获取用户积分，用户ID:', userId)
    
    const response = await getUserTotalPoints(userId)
    console.log('用户积分API响应:', response)
    
    if (response.code === 200) {
      const pointsData = response.data.data
      console.log('用户积分:',currentDetail.currentPoints)
      return {
        currentPoints: pointsData.totalPoints || 0,
        totalPoints: pointsData.historyTotalPoints || 0,
        availablePoints: pointsData.withdrawalPoints || 0,
        withdrawnPoints: pointsData.withdrawnPoints || 0
      }
    } else {
      showMessage('获取用户积分失败: ' + (response.msg || '未知错误'), 'error')
      return null
    }
  } catch (error) {
    console.error('获取用户积分失败:', error)
    showMessage('获取用户积分失败，请稍后重试', 'error')
    return null
  } finally {
    currentDetail.pointsLoading = false
  }
}

// 状态映射：前端状态到后端状态
const mapFrontendStatusToBackend = (status) => {
  switch (status) {
    case 'pending': return Status.Pending // 待管理员审核
    case 'approved': return Status.Processing // 待打款
    case 'rejected': return Status.Fail // 已驳回
    case 'paid': return Status.Success // 已打款
    case 'invalid': return Status.Fail // 无效状态映射到失败
    default: return undefined
  }
}

// 状态映射：后端状态到前端状态
const mapBackendStatusToFrontend = (status) => {
  // 添加空值检查
  if (status === undefined || status === null) return 0
  
  // 转换为大写以确保匹配
  const statusUpper = String(status).toUpperCase()
  
  switch (statusUpper) {
    case Status.Processing.toUpperCase(): return 1 // 待打款
    case Status.Fail.toUpperCase(): return 2 // 已驳回
    case Status.Success.toUpperCase(): return 4 // 已打款
    default: return 0 // 待审核
  }
}

// 计算属性
const filteredData = computed(() => {
  let data = [...tableData.value]
  
  // 根据筛选标签筛选
  if (activeFilter.value) {
    data = data.filter(item => {
      if (activeFilter.value === 'pending') return item.status === 0
      if (activeFilter.value === 'approved') return item.status === 1
      if (activeFilter.value === 'rejected') return item.status === 2
      if (activeFilter.value === 'paid') return item.status === 4
      if (activeFilter.value === 'invalid') return item.status === 5
      return true
    })
  }
  
  // 根据搜索条件筛选
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    data = data.filter(item => 
      item.id.toString().includes(keyword) || 
      (item.userName && item.userName.toLowerCase().includes(keyword))
    )
  }
  
  if (searchForm.status) {
    data = data.filter(item => {
      if (searchForm.status === 'pending') return item.status === 0
      if (searchForm.status === 'approved') return item.status === 1
      if (searchForm.status === 'rejected') return item.status === 2
      if (searchForm.status === 'paid') return item.status === 4
      if (searchForm.status === 'invalid') return item.status === 5
      return true
    })
  }
  
  // 日期筛选
  if (searchForm.startDate && searchForm.endDate) {
    // 这里简化处理，实际应根据任务创建时间筛选
    data = data.filter(item => {
      return true
    })
  }
  
  pagination.total = data.length
  return data
})

const paginatedData = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  const endIndex = startIndex + pagination.pageSize
  return filteredData.value.slice(startIndex, endIndex)
})

const totalPages = computed(() => {
  return Math.ceil(pagination.total / pagination.pageSize)
})

const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let start = Math.max(1, pagination.currentPage - Math.floor(maxVisible / 2))
  let end = Math.min(totalPages.value, start + maxVisible - 1)
  
  if (end - start < maxVisible - 1) {
    start = Math.max(1, end - maxVisible + 1)
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

const paginationStart = computed(() => {
  return (pagination.currentPage - 1) * pagination.pageSize + 1
})

const paginationEnd = computed(() => {
  const end = pagination.currentPage * pagination.pageSize
  return end > pagination.total ? pagination.total : end
})

const isAllSelected = computed(() => {
  return paginatedData.value.length > 0 && 
         paginatedData.value.every(row => selectedRows.value.includes(row))
})

// 方法
const setActiveFilter = (filter) => {
  activeFilter.value = filter
  pagination.currentPage = 1
  updateStats()
  fetchWithdrawalList()
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchWithdrawalList()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  searchForm.status = ''
  pagination.currentPage = 1
  selectedRows.value = []
  fetchWithdrawalList()
}

// 删除功能
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    showMessage('请选择要删除的申请', 'error')
    return
  }
  
  deleteConfirmMessage.value = `确定要删除选中的 ${selectedRows.value.length} 条提现申请吗？此操作不可撤销。`
  deleteConfirmVisible.value = true
}

// 导出功能
const handleExport = () => {
  exportDialogVisible.value = true
}

const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value || page === pagination.currentPage) return
  pagination.currentPage = page
  fetchWithdrawalList()
}

const handleSizeChange = () => {
  pagination.currentPage = 1
  fetchWithdrawalList()
}

const formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const formatNumber = (num) => {
  return num.toLocaleString('zh-CN')
}

const formatDateTime = (dateTime) => {
  return dateTime.replace(' ', '  ')
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '待打款'
    case 2: return '已驳回'
    case 4: return '已打款'
    default: return '未知'
  }
}

const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    case 4: return 'status-paid'
    default: return ''
  }
}

const isRowSelected = (row) => {
  return selectedRows.value.includes(row)
}

const toggleRowSelection = (row) => {
  const index = selectedRows.value.indexOf(row)
  if (index > -1) {
    selectedRows.value.splice(index, 1)
  } else {
    selectedRows.value.push(row)
  }
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedRows.value = []
  } else {
    selectedRows.value = [...paginatedData.value]
  }
}

const handleApprove = (row) => {
  confirmMessage.value = '确认通过该用户的提现申请吗？'
  confirmActionType.value = 'approve'
  currentActionItem.value = row
  confirmDialogVisible.value = true
}

const handleReject = (row) => {
  confirmMessage.value = '确认驳回该用户的提现申请吗？'
  confirmActionType.value = 'reject'
  currentActionItem.value = row
  confirmDialogVisible.value = true
}

// 无效功能
const handleInvalid = (row) => {
  confirmMessage.value = '确认将该用户的提现申请标记为无效吗？'
  confirmActionType.value = 'invalid'
  currentActionItem.value = row
  confirmDialogVisible.value = true
}

const handlePay = (row) => {
  confirmMessage.value = '确认已给该用户打款的提现申请吗？'
  confirmActionType.value = 'pay'
  currentActionItem.value = row
  confirmDialogVisible.value = true
}

const handleRevoke = (row) => {
  confirmMessage.value = '确认撤销驳回该用户的提现申请吗？'
  confirmActionType.value = 'revoke'
  currentActionItem.value = row
  confirmDialogVisible.value = true
}

const handleBatchApprove = () => {
  if (selectedRows.value.length === 0) {
    showMessage('请选择要操作的申请', 'error')
    return
  }
  
  confirmMessage.value = `确认通过选中的 ${selectedRows.value.length} 条提现申请吗？`
  confirmActionType.value = 'batch-approve'
  confirmDialogVisible.value = true
}

const handleBatchReject = () => {
  if (selectedRows.value.length === 0) {
    showMessage('请选择要操作的申请', 'error')
    return
  }
  
  confirmMessage.value = `确认驳回选中的 ${selectedRows.value.length} 条提现申请吗？`
  confirmActionType.value = 'batch-reject'
  confirmDialogVisible.value = true
}

// 批量无效功能
const handleBatchInvalid = () => {
  if (selectedRows.value.length === 0) {
    showMessage('请选择要操作的申请', 'error')
    return
  }
  
  confirmMessage.value = `确认将选中的 ${selectedRows.value.length} 条提现申请标记为无效吗？`
  confirmActionType.value = 'batch-invalid'
  confirmDialogVisible.value = true
}

const confirmAction = async () => {
  try {
    loading.value = true
    
    switch (confirmActionType.value) {
      case 'approve':
        // 调用API更新状态
        await updateWithdrawalStatus({
          id: parseInt(currentActionItem.value.id),
          status: Status.Processing
        })
        currentActionItem.value.status = 1
        currentActionItem.value.statusText = getStatusText(1)
        currentActionItem.value.statusClass = getStatusClass(1)
        showMessage('审核通过成功', 'success')
        break
        
      case 'reject':
        await updateWithdrawalStatus({
          id: currentActionItem.value.id,
          status: Status.Fail
        })
        currentActionItem.value.status = 2
        currentActionItem.value.statusText = getStatusText(2)
        currentActionItem.value.statusClass = getStatusClass(2)
        showMessage('审核驳回成功', 'success')
        break
        
      case 'invalid':
        await updateWithdrawalStatus({
          id: currentActionItem.value.id,
          status: Status.Fail
        })
        currentActionItem.value.status = 5
        currentActionItem.value.statusText = getStatusText(5)
        currentActionItem.value.statusClass = getStatusClass(5)
        showMessage('标记无效成功', 'success')
        break
        
      case 'pay':
        await updateWithdrawalStatus({
          id: currentActionItem.value.id,
          status: Status.Success
        })
        currentActionItem.value.status = 4
        currentActionItem.value.statusText = getStatusText(4)
        currentActionItem.value.statusClass = getStatusClass(4)
        showMessage('打款确认成功', 'success')
        break
        
      case 'revoke':
        await updateWithdrawalStatus({
          id: currentActionItem.value.id,
          status: Status.Pending
        })
        currentActionItem.value.status = 0
        currentActionItem.value.statusText = getStatusText(0)
        currentActionItem.value.statusClass = getStatusClass(0)
        showMessage('撤销驳回成功', 'success')
        break
        
      case 'batch-approve':
        // 批量操作API调用
        for (const row of selectedRows.value) {
          await updateWithdrawalStatus({
            id: row.id,
            status: Status.Processing
          })
          row.status = 1
          row.statusText = getStatusText(1)
          row.statusClass = getStatusClass(1)
        }
        showMessage(`批量通过 ${selectedRows.value.length} 条申请成功`, 'success')
        selectedRows.value = []
        break
        
      case 'batch-reject':
        for (const row of selectedRows.value) {
          await updateWithdrawalStatus({
            id: row.id,
            status: Status.Fail
          })
          row.status = 2
          row.statusText = getStatusText(2)
          row.statusClass = getStatusClass(2)
        }
        showMessage(`批量驳回 ${selectedRows.value.length} 条申请成功`, 'success')
        selectedRows.value = []
        break
        
      case 'batch-invalid':
        for (const row of selectedRows.value) {
          await updateWithdrawalStatus({
            id: row.id,
            status: Status.Fail
          })
          row.status = 5
          row.statusText = getStatusText(5)
          row.statusClass = getStatusClass(5)
        }
        showMessage(`批量标记无效 ${selectedRows.value.length} 条申请成功`, 'success')
        selectedRows.value = []
        break
    }
    
    updateStats()
    confirmDialogVisible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    showMessage('操作失败', 'error')
  } finally {
    loading.value = false
  }
}

// 删除确认功能
const confirmDelete = async () => {
  try {
    loading.value = true
    
    // 循环删除选中的记录
    for (const row of selectedRows.value) {
      const response = await deleteWithdrawal(row.id)
      
      if (response.code !== 200) {
        throw new Error(`删除ID ${row.id} 失败: ${response.msg}`)
      }
    }
    
    showMessage(`成功删除 ${selectedRows.value.length} 条申请`, 'success')
    
    // 重新获取数据
    await fetchWithdrawalList()
    
    selectedRows.value = []
    deleteConfirmVisible.value = false
  } catch (error) {
    console.error('删除失败:', error)
    showMessage(`删除失败: ${error.message}`, 'error')
  } finally {
    loading.value = false
  }
}

// 导出确认功能
const confirmExport = async () => {
  try {
    exportLoading.value = true
    let exportData = []
    if (exportForm.range === 'all') {
      exportData = filteredData.value
    } else if (exportForm.range === 'current') {
      exportData = paginatedData.value
    } else if (exportForm.range === 'selected') {
      exportData = selectedRows.value
    }
    // 模拟导出过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    showMessage(`成功导出 ${exportData.length} 条数据为${exportForm.format === 'excel' ? 'Excel' : 'CSV'}格式`, 'success')
    exportDialogVisible.value = false
  } catch (error) {
    showMessage('导出失败', 'error')
  } finally {
    exportLoading.value = false
  }
}

// 详情处理方法
const handleDetail = async (item) => {
  try {
    detailLoading.value = true
    
    // 设置基本信息
    Object.assign(currentDetail, {
      id: item.id,
      contact: item.phone,
      applyTime: item.applyTime,
      applicant: item.userName,
      registerDuration: '1个月',
      amount: item.amount,
      account: '418959526',
      status: item.status,
      statusText: getStatusText(item.status),
      statusClass: getStatusClass(item.status),
      fee: 0.00,
      age: 25,
      wechatAccount: '15489565477',
      expectedAmount: item.amount,
      gender: '男',
      withdrawMethod: '公众号提现',
      currentPoints: 0,
      totalPoints: 0,
      availablePoints: 0,
      withdrawnPoints: 0,
      historyRecords: [
        {
          id: '1526458478515264584785',
          amount: 100.00,
          applyTime: '2025-01-08 20:02',
          withdrawTime: '2025-01-08 20:02',
          status: 4
        }
      ],
      pointsLoading: true
    })
    
    detailDialogVisible.value = true
    
    // 获取用户积分数据
    const pointsData = await fetchUserPoints(item.userId || item.id)
    if (pointsData) {
      Object.assign(currentDetail, pointsData)
    }
    
  } catch (error) {
    console.error('处理详情失败:', error)
    showMessage('加载详情失败', 'error')
  } finally {
    detailLoading.value = false
    currentDetail.pointsLoading = false
  }
}

const closeConfirmDialog = () => {
  confirmDialogVisible.value = false
  confirmActionType.value = ''
  currentActionItem.value = null
}

const closeDeleteConfirm = () => {
  deleteConfirmVisible.value = false
  deleteConfirmMessage.value = ''
}

const closeExportDialog = () => {
  exportDialogVisible.value = false
  exportForm.range = 'current'
  exportForm.format = 'excel'
}

const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

const handleCloseAuditDialog = () => {
  auditDialogVisible.value = false
  auditForm.remark = ''
}

const submitAudit = async () => {
  if (!auditForm.remark) {
    showMessage('请输入审核意见', 'error')
    return
  }
  
  try {
    auditLoading.value = true
    
    // 映射审核结果到后端状态值
    let status
    switch (auditForm.result) {
      case 'approve':
        status = Status.Processing // 待打款
        break
      case 'reject':
        status = Status.Fail // 已驳回
        break
      case 'invalid':
        status = Status.Fail // 无效映射为失败
        break
      default:
        status = Status.Processing
    }
    
    // 发送审核请求
    const response = await updateWithdrawalStatus({
      id: parseInt(auditForm.id),
      status: status
    })
    
    if (response.code === 200) {
      // 审核成功后更新本地数据
      const record = tableData.value.find(item => item.id === parseInt(auditForm.id))
      if (record) {
        if (auditForm.result === 'approve') {
          record.status = 1
        } else if (auditForm.result === 'reject') {
          record.status = 2
        } else if (auditForm.result === 'invalid') {
          record.status = 5
        }
        record.statusText = getStatusText(record.status)
        record.statusClass = getStatusClass(record.status)
      }
      
      showMessage(`审核${auditForm.result === 'approve' ? '通过' : auditForm.result === 'reject' ? '驳回' : '无效'}成功`, 'success')
      auditDialogVisible.value = false
      updateStats()
      fetchWithdrawalList() // 重新获取数据以确保一致性
    } else {
      throw new Error(response.msg || '审核失败')
    }
  } catch (error) {
    console.error('审核请求失败:', error)
    showMessage(`审核失败: ${error.message || '网络错误'}`, 'error')
  } finally {
    auditLoading.value = false
  }
}

const closePayConfirm = () => {
  payConfirmVisible.value = false
  currentPayItem.value = null
}

const confirmPay = () => {
  if (currentPayItem.value) {
    currentPayItem.value.status = 4
    currentPayItem.value.statusText = getStatusText(4)
    currentPayItem.value.statusClass = getStatusClass(4)
    showMessage('打款成功', 'success')
    payConfirmVisible.value = false
    currentPayItem.value = null
    updateStats()
  }
}

const showMessage = (text, type = 'info') => {
  message.text = text
  message.type = type
  message.visible = true
  
  setTimeout(() => {
    message.visible = false
  }, 3000)
}

// 更新统计数据
const updateStats = () => {
  // 计算待审核数量
  stats.pending = tableData.value.filter(item => item.status === 0).length
  // 计算已审核数量（包括已打款、已驳回和无效）
  stats.audited = tableData.value.filter(item => item.status === 1 || item.status === 2 || item.status === 5).length
  // 计算总提现金额
  stats.totalAmount = tableData.value.reduce((sum, item) => sum + item.amount, 0)
}

onMounted(() => {
  fetchWithdrawalList()
})

// 监听筛选条件变化
watch([() => searchForm.keyword, () => searchForm.startDate, () => searchForm.endDate, () => searchForm.status, () => activeFilter.value], () => {
  pagination.currentPage = 1
})
</script>

<style scoped>
.withdraw-audit-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.stats-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.filter-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-tab {
  padding: 8px 16px;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  transition: all 0.3s;
}

.filter-tab.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}

.filter-tab:hover:not(.active) {
  background: #f5f7fa;
}

.search-form {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-input {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  width: 200px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-select {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  width: 200px;
  background: white;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-separator {
  color: #606266;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  padding-bottom: 8px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-secondary {
  background-color: #909399;
  color: white;
}

.btn-secondary:hover {
  background-color: #a6a9ad;
}

.btn-danger {
  background-color: #f56c6c;
  color: white;
}

.btn-danger:hover {
  background-color: #f78989;
}

.btn-warning {
  background-color: #e6a23c;
  color: white;
}

.btn-warning:hover {
  background-color: #ebb563;
}

.btn-success {
  background-color: #67c23a;
  color: white;
}

.btn-success:hover {
  background-color: #85ce61;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-text {
  background: transparent;
  color: #409eff;
}

.btn-text:hover {
  background: #ecf5ff;
}

.batch-actions {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.batch-info {
  color: #1890ff;
  font-size: 14px;
  font-weight: 500;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.table-wrapper {
  position: relative;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th, .data-table td {
  padding: 12px 16px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}

.data-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.data-table tr:hover {
  background-color: #f5f7fa;
}

.data-table tr.selected {
  background-color: #f0f9ff;
}

.data-table tr.row-disabled {
  opacity: 0.6;
}

.checkbox-col {
  width: 40px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-approved {
  background-color: #f0f9ff;
  color: #409eff;
}

.status-rejected {
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-paid {
  background-color: #f0f9eb;
  color: #67c23a;
}

.highlight {
  color: #f56c6c;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-size-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.pagination-btn, .page-number {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  background: #fff;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 40px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-btn:hover:not(:disabled),
.page-number:hover:not(.active) {
  background: #f5f7fa;
}

.pagination-btn:disabled,
.page-number:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.page-number.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 800px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.modal-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #909399;
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

.confirm-modal, .delete-confirm-modal, .pay-confirm-modal {
  width: 400px;
}

.confirm-text, .delete-confirm-text, .pay-confirm-text {
  text-align: center;
  font-size: 16px;
  margin-bottom: 20px;
  color: #303133;
}

.confirm-buttons, .delete-confirm-buttons, .pay-confirm-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.export-modal, .detail-modal {
  width: 800px;
}

.export-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-label {
  font-weight: 500;
  color: #303133;
}

.required {
  color: #f56c6c;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.radio-custom {
  width: 16px;
  height: 16px;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  display: inline-block;
  position: relative;
}

.radio-label input[type="radio"]:checked + .radio-custom {
  border-color: #409eff;
  background-color: #409eff;
}

.radio-label input[type="radio"]:checked + .radio-custom::after {
  content: '';
  width: 6px;
  height: 6px;
  background: white;
  border-radius: 50%;
  position: absolute;
  top: 3px;
  left: 3px;
}

.audit-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.amount-input {
  position: relative;
}

.amount-suffix {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
}

.form-textarea {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  resize: vertical;
  min-height: 80px;
}

.textarea-counter {
  text-align: right;
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.info-label {
  color: #606266;
  font-size: 14px;
}

.info-value {
  color: #303133;
  font-size: 14px;
}

.points-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.points-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.points-label {
  color: #606266;
  font-size: 12px;
  margin-bottom: 5px;
}

.points-value {
  color: #303133;
  font-size: 16px;
  font-weight: bold;
}

.loading-text {
  color: #909399;
  font-style: italic;
}

.history-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.history-table th, .history-table td {
  padding: 12px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}

.history-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 1001;
  animation: slideIn 0.3s ease;
}

.message.success {
  background: #f0f9ff;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.message.error {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.message.info {
  background: #f4f4f5;
  color: #909399;
  border: 1px solid #e9e9eb;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .stats-container {
    flex-direction: column;
  }
  
  .form-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-input, .form-select {
    width: 100%;
  }
  
  .date-range {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .batch-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 15px;
    align-items: center;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .points-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .modal-content {
    width: 95vw;
  }
  
  .confirm-modal, .delete-confirm-modal, .pay-confirm-modal {
    width: 90vw;
  }
}
</style>
